package com.bailong.nanny.util;

import com.bailong.nanny.entity.Admin;
import com.bailong.nanny.entity.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtils {
    //连接池对象
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");

    private static QueryRunner runner = new QueryRunner(dataSource);
    /**
     * 查询多条数据
     * @param clazz
     * @param sql
     * @param objects
     * @param <T>
     * @return
     */
    public static <T> List<T> queryList(Class clazz,String sql,Object...objects)
    {
        try {
            return runner.query(sql,new BeanListHandler<T>(clazz),objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * 查询单条
     * @param clazz
     * @param sql
     * @param objects
     * @param <T>
     * @return
     */
    public static <T> User queryOne(Class clazz, String sql, Object...objects)
    {
        try {
            return (User) runner.query(sql,new BeanHandler<T>(clazz),objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * 查询单条
     * @param clazz
     * @param sql
     * @param objects
     * @param <T>
     * @return
     */
    public static <T> Admin Login(Class clazz, String sql, Object...objects)
    {
        try {
            return (Admin) runner.query(sql,new BeanHandler<T>(clazz),objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 增删改操作
     * @param sql
     * @param objects
     * @return
     */
    public static int update(String sql,Object...objects){
        try {
            return runner.update(sql,objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 查询行数
     * @param sql
     * @param objects
     * @return
     */
    public static int queryCount(String sql,Object...objects){

        try {
            //自定义resultset，对结果集进行操作
            return runner.query(sql, new ResultSetHandler<Integer>() {
                @Override
                public Integer handle(ResultSet resultSet) throws SQLException {
                    //将数据游标指向第一行
                    resultSet.next();
                    //返回唯一的一列数据
                    return resultSet.getInt(1);
                }
            },objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
